import { useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'
import { type RootState } from '@/store'
import { type MenuState } from '@/store/modules/menu'
import { type MenuItem } from '@/store/modules/menu/type'

// 生成的面包屑数组
let breadcrumb: { title: string; url: string; }[] = []
// 路由路径
let path: string

// 用于生成最终结果
const createBreadcrumb = (menuList: MenuItem[]) => {
    menuList.forEach(item => {
        if (!item.key) {
            createBreadcrumb(item!.children as MenuItem[])
        } else if (Reflect.has(item as Object, 'children') && path.includes(item!.key as string)) {
            breadcrumb.push({ title: item.label as string, url: item.key as string })
            createBreadcrumb(item!.children as MenuItem[])
        } else if (item!.key === path) {
            breadcrumb.push({ title: item.label as string, url: item.key as string })
            return
        }
    })
}

export const useBreadcrumb = () => {
    // 菜单列表
    const { menuList } = useSelector<RootState, MenuState>((state) => state.menu)
    // 路由路径
    const { pathname } = useLocation()
    path = pathname

    breadcrumb = []
    createBreadcrumb(menuList)

    return [...new Set(breadcrumb)]
}